import request from '@/utils/request'
import { Message } from 'element-ui'

export function doDownload(url, data, filename) {
  return new Promise((resolve, reject) => {
    request({
      method: 'post',
      url: url,
      data: data,
      timeout: 600000,
      responseType: 'blob' // 指定获取数据的类型为blob
    }).then(
      function(response) {
        if (response.type === 'application/json') {
          const reader = new FileReader()
          reader.readAsText(response)
          reader.onload = function() {
            const msg = JSON.parse(reader.result) // 此处的msg就是后端返回的msg内容
            if (msg.code === '-500') {
              Message({
                message: msg.result,
                type: 'error',
                duration: 3 * 1000
              })
            }
            if (msg.code === '-1') {
              Message({
                message: '系统错误!',
                type: 'error',
                duration: 3 * 1000
              })
            }
          }
          reject()
        } else {
          // console.log('response:' + response)
          // 创建a标签并点击， 即触发下载
          const url = window.URL.createObjectURL(response)
          const link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', filename)
          document.body.appendChild(link)
          link.click()
          URL.revokeObjectURL(link.href) // 释放URL 对象
          document.body.removeChild(link)
          resolve()
        }
      }
    ).catch(function(err) {
      console.log(err)
      reject()
    })
  })
}
